/* eslint-disable prettier/prettier */
import React, {Component} from 'react';

import {
  StyleSheet,
  Text,
  View,
  Platform,
  Button,
  Alert,
  ActivityIndicator,
} from 'react-native';

import OpenFile from 'react-native-doc-viewer';

import RNFS from 'react-native-fs';

//保存路径可以跳进去看，具体自己选择

var SavePath =
  Platform.OS === 'ios'
    ? RNFS.LibraryDirectoryPath
    : RNFS.ExternalDirectoryPath;

export default class Component extends Component {
  static navigationOptions = ({navigation}) => ({
    title: `${navigation.state.params.name}`,
  });

  state = {animating: false};

  //首先下载文件

  componentDidMount() {
    alert('开始');

    RNFS.exists(SavePath + 'demo.docx')
      .then(
        //判断文件是否已存在，返回result为true说明存在，result为false说明不存在

        (result) => {
          console.log(result);

          if (!result) {
            var DownloadFileOptions = {
              fromUrl: 'https://calibre-ebook.com/downloads/demos/demo.docx', // 下载文件的URL

              toFile: SavePath + '/demo.docx', // 将文件保存到的本地文件系统路径 //进度条
              begin: (res) => {
                console.log('begin', res);

                console.log(
                  'contentLength:',
                  res.contentLength / 1024 / 1024,
                  'M',
                );
              },

              progress: (res) => {
                let pro = res.bytesWritten / res.contentLength;

                console.log(pro);
              },
            };

            const ret = RNFS.downloadFile(DownloadFileOptions);

            ret.promise
              .then((res) => {
                console.log('success', res);

                console.log('file://' + DownloadFileOptions.toFile);
              })
              .catch((err) => {
                console.log('err', err);
              });
          }
        },
      )
      .catch();
  }

  //打开本地文件

  handlePressLocal = () => {
    this.setState({animating: true});

    if (Platform.OS === 'ios') {
      OpenFile.openDoc(
        [
          {
            url: SavePath + '/demo.docx',

            fileNameOptional: '白皮书',
          },
        ],
        (error, url) => {
          if (error) {
            this.setState({animating: false});
          } else {
            this.setState({animating: false});

            console.log(url);
          }
        },
      );
    } else {
      OpenFile.openDoc(
        [
          {
            url: 'file://' + SavePath + '/demo.docx', //打开本地文件必须加上file://

            fileName: '白皮书',

            cache: true,

            fileType: 'docx',
          },
        ],
        (error, url) => {
          if (error) {
            console.log(error);

            this.setState({animating: false});
          } else {
            this.setState({animating: false});

            console.log(url);

            alert(url);
          }
        },
      );
    }
  };

  //打开远程文件

  handlePress = () => {
    this.setState({animating: true});

    if (Platform.OS === 'ios') {
      OpenFile.openDoc(
        [
          {
            url: 'https://calibre-ebook.com/downloads/demos/demo.docx',

            fileNameOptional: 'test filename',
          },
        ],
        (error, url) => {
          if (error) {
            this.setState({animating: false});
          } else {
            this.setState({animating: false});

            console.log(url);
          }
        },
      );
    } else {
      //Android

      this.setState({animating: true});

      OpenFile.openDoc(
        [
          {
            url:
              'https://www.huf-haus.com/fileadmin/Bilder/Header/ART_3/Header_HUF_Haus_ART_3___1_.jpg', // Local "file://" + filepath

            fileName: 'sample',

            cache: false,

            fileType: 'jpg',
          },
        ],
        (error, url) => {
          if (error) {
            this.setState({animating: false});

            console.error(error);
          } else {
            this.setState({animating: false});

            console.log(url);
          }
        },
      );
    }
  };

  setToggleTimeout() {
    this.setTimeout(() => {
      this.setState({animating: !this.state.animating});

      this.setToggleTimeout();
    }, 2000);
  }

  render() {
    return (
      <View style={styles.container}>

        <ActivityIndicator
          animating={this.state.animating}
          style={[styles.centering, {height: 80}]}
          size="large"
        />
         
        <Text style={styles.welcome}>
             Doc Viewer React Native      
        </Text>
        <Button
          onPress={this.handlePress.bind(this)}
          title="打开远程文档"
          accessibilityLabel="See a Document"
        />
        <Button
          onPress={this.handlePressLocal.bind(this)}
          title="打开本地文档"
          accessibilityLabel="See a Document"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

    backgroundColor: '#F5FCFF',
  },

  welcome: {
    fontSize: 20,

    textAlign: 'center',

    margin: 10,
  },

  instructions: {
    textAlign: 'center',

    color: '#333333',

    marginBottom: 5,
  },
});
